package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.entity.Administrator;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.mapper.AdministratorMapper;
import com.itheima.wisdomnext.service.AuthService;
import com.itheima.wisdomnext.util.AuthS_Util;
import com.itheima.wisdomnext.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class AuthServiceImpl implements AuthService  {

    @Autowired
    private AdministratorMapper administratorMapper;

    @Autowired
    private JwtUtil jwtUtil; // 使用 JwtUtil

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 管理员注册
    public void registerAdministrator(Administrator administrator)  {
        // 检查用户名是否已存在
        if (administratorMapper.existsByUsername(administrator.getUsername())) {
            AuthS_Util.isTrue(true,ErrorCode.FAILED,"Username is already taken");
        }

        // 获取当前年份的最后一位数字
        int currentYearLastDigit = Integer.parseInt(String.valueOf(java.time.LocalDate.now().getYear()+1).substring(3));

        // 生成一个 5 位的随机数字
        Random random = new Random();
        int randomFiveDigit = 10000 + random.nextInt(90000);  // 生成一个 5 位数字

        // 组合当前年最后一位和随机 5 位数字
        int randomAdminId = currentYearLastDigit * 100000 + randomFiveDigit;  // 拼接成新的 adminId

        // 创建新管理员并设置属性
        Administrator admin = new Administrator();
        admin.setAdminId(randomAdminId);
        admin.setUsername(administrator.getUsername());
        admin.setPassword(passwordEncoder.encode(administrator.getPassword())); // 密码加密
        admin.setRole(administrator.getRole());
        admin.setIsActive(administrator.getIsActive());

        // 将新管理员插入数据库
        int i = administratorMapper.insertAdministrator(admin);
        if (!(i > 0)) {
            AuthS_Util.isTrue(true,ErrorCode.FAILED,"插入失败");
        }
    }

    // 管理员登录
    public String loginAdministrator(Administrator administrator)  {
        // 查找管理员
        Administrator admin = administratorMapper.findByUsername(administrator.getUsername());

        // 如果管理员不存在，抛出异常
        if (admin == null) {
            AuthS_Util.isTrue(true,ErrorCode.LOGIN_ACCOUNT_ERROR,"管理员不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(administrator.getPassword(), admin.getPassword())) {
            AuthS_Util.isTrue(true,ErrorCode.LOGIN_ACCOUNT_ERROR,"密码错误");
        }

        // 获取 adminId
        int adminId = admin.getAdminId();

        // 使用 JwtUtil 生成 Token
        String token = jwtUtil.generateToken(admin.getUsername()); // 生成并返回 JWT 令牌

        // 返回 JWT 和 adminId
        return "Token: " + token + ", adminId: " + adminId;
    }
}
